package com.plugin.serial;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import org.winplus.serial.utils.ISerialPortCallback;
import org.winplus.serial.utils.SerialPort;

import com.szcf.testserial.utils.Constants;
import com.szcf.testserial.utils.Command;
import com.szcf.testserial.utils.HexUtils;
import android.util.Log;
/**
 * This class echoes a string called from JavaScript.
 */
public class SerialPlugin extends CordovaPlugin implements ISerialPortCallback {

   private SerialPort serialPort;
   private CallbackContext callbackContextMethod;
   private String sendCode = "";
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("coolMethod")) {
            String message = args.getString(0);
            this.coolMethod(message, callbackContext);
            return true;
        }else if (action.equals("plus")) {//主方法中增加一段方法名称判断和调用的代码
            int x = args.getInt(0);
            int y = args.getInt(1);
            this.plus(x, y, callbackContext);
            return true;
        }else if (action.equals("openSerial")) {//主方法中增加一段方法名称判断和调用的代码
            String Yn = args.getString(0);
            String Xn = args.getString(1);
            String serialName = args.getString(2);
            // callbackContext.success(Yn+"__"+Xn+"__"+serialName);
            this.sendSerial(Yn, Xn, serialName, callbackContext);
            return true;
        }
        return false;
    }

    private void coolMethod(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) {
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
	//新增一个传入两个参数求和的方法
    private void plus(int x, int y, CallbackContext callbackContext) {
        callbackContext.success(x + y);
    }


    public void sendSerial(String Yn, String Xn, String serialName,CallbackContext callbackContext){   
        callbackContextMethod = callbackContext;
        openSerial(serialName);
        serialSend(Command.sendCommandGoods(Yn, Xn, "01"));	
    }
    

    /* 打开串口设备 */
    public void openSerial(String serialName) {
      try {
        if (serialPort == null) {		// 初始化串口对象
          serialPort = new SerialPort(this);
        //   serialPort.openPort(Constants.SERIAL_DEVICE_NAME, Constants.SERIAL_BAUDRATE, 0);
          serialPort.openPort(serialName, Constants.SERIAL_BAUDRATE, 0);
        }
      } catch (Exception e) {        
        callbackContextMethod.error("串口打开失败");
        e.printStackTrace();
      }
    }

    /* 串口发送byte[]数据 */
    public boolean serialSend(byte[] data) {
      if (serialPort == null) return false;
      return serialPort.send(data);
    }

    /* 串口发送String数据 */
    public boolean serialSend(String data) {
      Log.e("", "serial send==================================================="+data);
      sendCode = data;
      if (serialPort == null) return false;
      return serialPort.send(HexUtils.hexStringToBytes(data));
    }

    /**
     * 收到串口数据，回调
     */
    @Override
    public int onReadData(String device, byte[] data, int offset, int len) {
      // TODO Auto-generated method stub
      String returnDate  = bytesToHexString(data);
      if(returnDate.indexOf("fe")>0){
        callbackContextMethod.success(sendCode + "," + returnDate);
        serialPort.closePort();
        serialPort = null;
      }
      return 0;
    }

    /*     Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)来转换成16进制字符串。
			* @param src byte[] data  */

	public static String bytesToHexString(byte[] src){
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}
}
